package com.wxx.socket.server;

import com.wxx.socket.BroadcastUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

/**
 * socket数据处理
 *
 * @author 万祥新
 *
 */
public class SocketChannelHandler extends SimpleChannelInboundHandler<String> {
    public static ChannelGroup socketGroup = new DefaultChannelGroup("socket", GlobalEventExecutor.INSTANCE);

    @Override
    protected void channelRead0(ChannelHandlerContext arg0, String arg1) {
        System.out.println("Socket接收到了数据>>>" + arg1);
        BroadcastUtil.broadcastToAll(arg1);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        System.out.println("Socket新用户连接了");
        socketGroup.add(ctx.channel());
        BroadcastUtil.broadcastToAll("Socket新用户连接了");
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx){
        System.out.println("Socket用户退出了");
        socketGroup.remove(ctx.channel());
        BroadcastUtil.broadcastToAll("Socket用户退出了");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        Channel channel = ctx.channel();
        socketGroup.remove(channel);
        if (channel.isActive()) {
            ctx.close();
        }
    }
}
